"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 非512整数倍读写
Case Name   : 支持非512整数倍的读和写，设置max_prepared_transactions=0，非512整数倍写失败
Create At   : 2023/4/19
Owner       : opentestcase033
Description :
    1.设置max_prepared_transactions=0，重启集群
    2.创建表
    3.启动一个事务，插入数据，prepare transaction
    4.dsscmd查询数据是否存在
    5.清理环境
Expect      :
    1.设置成功
    2.建表成功
    3.启动事务，插入数据成功，准备事务提交失败
    4.数据不存在
    5.清理成功
History     :
"""

import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant


class WriteRead(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.common = Common('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_write_read_0005'
        self.max_pts = self.common.show_param('max_prepared_transactions')

    def test_write_read(self):
        text1 = '-----step1:设置max_prepared_transactions=0，重启集群;expect:成功-----'
        self.log.info(text1)
        guc_res = self.pri_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            'max_prepared_transactions=0')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f"设置参数失败:{text1}")
        restart_db = self.pri_sh.restart_db_cluster()
        self.log.info(restart_db)
        self.assertTrue(restart_db, f"重启数据库失败:{text1}")
        switch_res = self.pri_sh.exec_cm_ctl('switchover', '-a')
        self.log.info(switch_res)
        self.assertIn(self.constant.cm_switchover_success_msg, switch_res,
                      f"switchover -a 失败:{text1}")

        text2 = '-----step2:建表;expect:建表成功-----'
        self.log.info(text2)
        create_tb = f"drop table if exists {self.tb_name} cascade;" \
                    f"create table {self.tb_name}(" \
                    f"id int, name text)with(segment=on);"
        create_tb_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_tb_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_tb_res,
                      f"执行失败:{text2}")

        text3 = '-----step3:启动一个事务，插入数据，prepare transaction;' \
                'expect:prepare报错-----'
        self.log.info(text3)
        sql1 = f"""begin;
        insert into {self.tb_name} values(1, 'aaa');
        prepare transaction 'test_begin';"""
        sql1_res = self.pri_sh.execut_db_sql(sql1)
        self.log.info(sql1_res)
        self.assertIn('BEGIN', sql1_res, f"执行失败:{text2}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, sql1_res,
                      f"执行失败:{text2}")
        self.assertNotIn(self.constant.PREPARED_TRANSACTION_MSG, sql1_res,
                         f"执行失败:{text2}")

        text4 = '-----step4:dsscmd查询数据;expect:数据不存在-----'
        self.log.info(text4)
        time.sleep(5)
        cmd = f"source {macro.DB_ENV_PATH};dsscmd ls -p +data/pg_twophase"
        self.log.info(cmd)
        dsscmd_res = self.pri_node.sh(cmd).result()
        self.log.info(dsscmd_res)
        self.assertIn('Succeed to ls dir info.', dsscmd_res.splitlines()[1],
                      f"执行失败:{text4}")

    def tearDown(self):
        text = '-----step5:清理环境 expect:成功-----'
        self.log.info(text)
        drop_tb_res = self.pri_sh.execut_db_sql(
            f"commit prepared 'test_begin';"
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_tb_res)
        guc_res = self.pri_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'max_prepared_transactions={self.max_pts}')
        self.log.info(guc_res)
        restart_db = self.pri_sh.restart_db_cluster()
        self.log.info(restart_db)
        self.assertTrue(guc_res, f"恢复max_prepared_transactions参数失败:{text}")
        self.assertTrue(restart_db, f"重启数据库失败:{text}")
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_tb_res,
                      f"执行失败:{text}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
